package org.netty.push.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;

/**
 *  消息服务启动类
 *  
 * @author zzh
 *
 */
public class NettyServer {
	Logger logger=LoggerFactory.getLogger(NettyServer.class);
	/**
	 * 链接线程池
	 */
	private EventLoopGroup parentGroup=new NioEventLoopGroup(2);
	/**
	 * 工作线程池
	 */
	private EventLoopGroup childGroup=new NioEventLoopGroup(4);
	
	/**
	 * 服务端口
	 */
	private int serverport=8088;
	
	public void start() {
		//1、设置服务启动辅助类
		ServerBootstrap serverBootstrap=new ServerBootstrap();
		
		//2、分别设置链接线程，工作线程
		serverBootstrap.group(parentGroup, childGroup);
		//3、设置IO类型
		serverBootstrap.channel(NioServerSocketChannel.class);
		//4、设置系统参数
		serverBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
		//5设置日志handler
		serverBootstrap.handler(new LoggingHandler());
		//6、初始化管道
		serverBootstrap.childHandler(new CustomerChannelInitializer());
		//绑定端口
		try {
			ChannelFuture cf = serverBootstrap.bind(serverport).sync();
		
			logger.info("\n server startup ................. port is {}",serverport);
			cf.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			logger.error("server start error ...."+e.getMessage(),e);
		}finally {
			parentGroup.shutdownGracefully();
			childGroup.shutdownGracefully();
		}
	}

}
